package cn.hx.admin.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil<T> {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Value("${spring.application.name}")
    private String projectName;

    /**
     * 清空当前项目的缓存
     */
    public void deleteKeys() {
        //获取以当前项目名开头的键
        Set<String> keys = redisTemplate.keys(projectName + "*");
        for (String key : keys) {
            redisTemplate.delete(key);//循环删除那些键
        }
    }


    /**
     * 存数据
     *
     * @param key 键
     * @param v   值
     */
    public void set(String key, T v) {
        redisTemplate.opsForValue().set(projectName + key, v);
    }

    /**
     * 根据键获取值
     *
     * @param key 键
     * @return 值
     */
    public T get(String key) {
        Object o = redisTemplate.opsForValue().get(projectName + key);
        return (T) o;
    }

    /**
     * 删除指定的键
     *
     * @param key
     */
    public void deleteKey(String key) {
        redisTemplate.delete(projectName + key);

    }

    /**
     * 删除指定的键表达式 后面一般用*结尾
     *
     * @param pattern
     */
    public void deleteKeys(String pattern) {
        Set<String> keys = redisTemplate.keys(projectName + pattern);
        for (String key : keys) {
            redisTemplate.delete(key);//循环删除那些键
        }
    }

    /**
     * 设置过期时间
     *
     * @param key      键
     * @param timeout  时间
     * @param timeUnit 单位
     */
    public void setExpire(String key, long timeout, TimeUnit timeUnit) {
        redisTemplate.expire(projectName + key, timeout, timeUnit);
    }
}